package net.lainiao.jwt.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.lainiao.jwt.bean.Login;
import net.lainiao.jwt.bean.ResponseData;
import net.lainiao.jwt.util.JWT;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2018/7/12.
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        String loginId=request.getHeader("loginId");

        if(StringUtils.isNotEmpty(token)&&StringUtils.isNotEmpty(loginId)){
            Login login= JWT.unsign(token,Login.class);
            if(login!=null&&login.getId()==Integer.parseInt(loginId)){
                return true;
            }
        }
        ResponseData responseData=ResponseData.forbidden();
        responseData.putDataValue("message","token没有通过验证");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out=response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseData);
        out.print(json);
        out.flush();
        out.close();
        return false;
    }
}
